package com.hjb.netty.chat;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;

public class ChatServer {

    public static void main(String[] args){

        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workGroup)
                    .channel(NioServerSocketChannel.class)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel){
                            //socketChannel.pipeline().addLast(new DelimiterBasedFrameDecoder(10000, Delimiters.lineDelimiter()));
                            //编码
                            socketChannel.pipeline().addLast(new StringDecoder(CharsetUtil.UTF_8));
                            //解码
                            socketChannel.pipeline().addLast(new StringEncoder(CharsetUtil.UTF_8));
                            //自定义处理
                            socketChannel.pipeline().addLast(new Myhandler());
                        }
                    });
            //绑定服务端口
            ChannelFuture channelFuture = bootstrap.bind(8099).sync();
            System.out.println("服务已启动，监听端口：8099");
            //开始接收客户连接
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            workGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }

    }
}
